const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID

  try {
    // 获取用户信息
    const userResult = await db.collection('users').where({
      _openid: openid
    }).get()

    if (userResult.data.length === 0) {
      return {
        success: false,
        message: '用户不存在'
      }
    }

    const user = userResult.data[0]

    // 获取所有会员等级配置
    const levelsResult = await db.collection('member_levels').orderBy('level', 'asc').get()

    // 获取当前会员等级详情
    const currentLevelResult = await db.collection('member_levels').where({
      level: user.memberLevel || 1
    }).get()

    const currentLevel = currentLevelResult.data[0] || {
      name: '普通会员',
      level: 1,
      upgradeCondition: { type: 'total_amount', value: 0 },
      discountRate: 1,
      pointsRate: 1,
      rights: ['基础权益']
    }

    // 计算升级进度
    const nextLevel = levelsResult.data.find(level => level.level > currentLevel.level)
    let upgradeProgress = 0
    let canUpgrade = false

    if (nextLevel) {
      const currentConsumption = user.totalConsumption || 0
      const requiredAmount = nextLevel.upgradeCondition.value
      upgradeProgress = Math.min((currentConsumption / requiredAmount) * 100, 100)
      canUpgrade = currentConsumption >= requiredAmount
    }

    return {
      success: true,
      data: {
        user: {
          _id: user._id,
          nickName: user.nickName,
          avatarUrl: user.avatarUrl,
          memberLevel: user.memberLevel || 1,
          totalConsumption: user.totalConsumption || 0
        },
        currentLevel,
        nextLevel,
        allLevels: levelsResult.data,
        upgradeProgress,
        canUpgrade
      }
    }
  } catch (error) {
    console.error('获取会员信息失败:', error)
    return {
      success: false,
      message: '获取会员信息失败'
    }
  }
}